package service

import (
	"ChdChat-Gin/model"
	"ChdChat-Gin/service/utils"
	"fmt"
	"time"
)

type Player struct {
	client *Client
	card   []int
}

type GameRoom struct {
	Master    string // 房主
	Password  string // 密码
	Member    map[string]*Player
	BroadCast chan model.ChatRoomMessage
	UsedCard  []int
}

type RoomManager struct {
	Rooms map[int]*GameRoom // 房间号为键，房间为值
}

var GameRoomManager *RoomManager

func InitGameRoomManager() error {
	GameRoomManager = &RoomManager{
		Rooms: make(map[int]*GameRoom),
	}
	return nil
}

func (rm *RoomManager) CreateRoom(account, password string) error {
	v, ok := ChatRoomManager.Clients[account]
	if !ok {
		return fmt.Errorf("please login first")
	}
	room := &GameRoom{
		Master:    account,
		Password:  password,
		Member:    make(map[string]*Player, 4),
		BroadCast: make(chan model.ChatRoomMessage),
	}
	room.Member[account] = &Player{
		client: v,
		card:   make([]int, 0),
	}
	l := len(rm.Rooms) // TODO 生成房间号的方式得改
	rm.Rooms[l] = room
	return nil
}

func (rm *RoomManager) JoinRoom(id int, account, password string) error {
	c, ok := ChatRoomManager.Clients[account]
	if !ok {
		return fmt.Errorf("please login first")
	}
	r, ok := rm.Rooms[id]
	if !ok {
		return fmt.Errorf("room not exist")
	}
	if password == r.Password {
		r.Member[account] = &Player{
			client: c,
			card:   make([]int, 0),
		}
	} else {
		return fmt.Errorf("room password wrong")
	}
	return nil
}

func (rm *RoomManager) NewGame(id int) error {
	card := utils.Licensing()
	cardStart, cardEnd := 0, 15 // 首个玩家发15张牌
	for _, v := range rm.Rooms[id].Member {
		playerCard := make([]int, cardEnd-cardStart)
		copy(playerCard, card[cardStart:cardEnd])
		msg := model.ChatRoomMessage{
			Type:     model.GAMEROOMMESSAGE,
			Data:     playerCard, // 取[start，end)区间内的牌发给玩家
			Date:     time.Now().Format("2006-01-02 15:04:05"),
			Sender:   "system",
			Receiver: v.client.ID,
		}
		v.card = playerCard
		v.client.Receiver <- msg

		// 下标向后移，发剩下的牌
		cardStart = cardEnd
		cardEnd += 13
	}
	return nil
}

func (gm *GameRoom) BroadCastGameMsg() {
	for {
		select {
		case msg, _ := <-gm.BroadCast:
			for _, conn := range gm.Member {
				conn.client.Receiver <- msg
			}
		}
	}
}
